import django
from .models import Users, Collections
import random
import requests
import numpy as np

base_url = 'http://113.31.110.212:4000'


def test_view(request):
    user = Users.objects.create(username='test', password='aaa',email='aaa')
    user.save()
    res = Users.objects.all()
    print(res.values())
    response = {'code':200,'data':list(res.values())}
    return JsonResponse(response)
    # return HttpResponse('Hello, World!')


def login_view(request):
    print("login_view")
    username = request.GET.get('username')
    password = request.GET.get('password')
    print(username,password)
    res = Users.objects.filter(username=username,password=password)
    print(res)
    if res:
        response = {'code':200,'data':list(res.values())}
    else:
        response = {'code':201,'data':[]}
    return JsonResponse(response)


def register_view(request):
    username = request.GET.get('username')
    password = request.GET.get('password')
    email = request.GET.get('email')
    res = Users.objects.filter(username=username)
    if res:
        response = {'code':201,'data':[]}
    else:
        user = Users.objects.create(username=username, password=password,email=email)
        user.save()
        response = {'code':200,'data':[{'username':username,'password':password,'email':email}]}
    return JsonResponse(response)


def add_collection_view(request):
    user_id = request.GET.get('user_id')
    song_id = request.GET.get('song_id')
    song_name = request.GET.get('song_name')
    song_url = request.GET.get('song_url')
    song_pic = request.GET.get('song_pic')
    res = Collections.objects.filter(user_id=user_id,song_id=song_id)
    print(res)
    if res:
        response = {'code':201,'data':[]}
        return JsonResponse(response)
    collection = Collections.objects.create(user_id=int(user_id), song_id=song_id,song_name=song_name,song_url=song_url,song_pic=song_pic)
    collection.save()
    response = {'code':200,'data':[{'user_id':user_id,'song_id':song_id,'song_name':song_name,'song_url':song_url,'song_pic':song_pic}]}
    return JsonResponse(response)

def get_collection_view(request):
    user_id = request.GET.get('user_id')
    res = Collections.objects.filter(user_id=user_id)
    response = {'code':200,'data':list(res.values())}
    return JsonResponse(response)

def delete_collection_view(request):
    user_id = request.GET.get('user_id')
    song_id = request.GET.get('song_id')
    res = Collections.objects.filter(user_id=user_id,song_id=song_id)
    if res:
        res.delete()
        response = {'code':200,'data':[]}
    else:
        response = {'code':201,'data':[]}
    return JsonResponse(response)


from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from django.http import JsonResponse

def recommend_view(request):
    user_id = request.GET.get('user_id')
    target_id = request.GET.get('user_id')
    # return JsonResponse({'data': [{"song_id":"408814900","song_name":"借我","song_url":"http://m801.music.126.net/20240220225927/8ef2105b03ce1f36d0803e65984a5750/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/28481791211/c4c9/0b75/2d1d/9ed6a813cac06784a45c359f6d4165c8.mp3","song_pics":"http://p2.music.126.net/Eg4cy0_HIF2nrX2gMCsWkQ==/17967119509636556.jpg"}],'code':200})

    user_song_ids = Collections.objects.filter(user_id=user_id).values_list('song_id', flat=True)

    all_users_song_ids = Collections.objects.exclude(user_id=user_id).values_list('song_id', flat=True)

    all_songs = list(set(user_song_ids) | set(all_users_song_ids))

    all_collections = Collections.objects.all()

    users = Users.objects.all()
    user_ids = users.values_list('user_id', flat=True)
    print("user_num",user_ids)  
    all_users_song_ids = np.zeros((max(user_ids)+1,len(all_songs)))

    for idx,user in enumerate(all_collections):
        user_id = user.user_id
        song_id = user.song_id
        index = all_songs.index(song_id)
        all_users_song_ids[user_id,index] = 1
    
    target_user_song_ids = np.zeros(len(all_songs))
    for index in range(len(all_songs)):
        if all_songs[index] in user_song_ids:
            target_user_song_ids[index] = 1
    similarity = cosine_similarity([target_user_song_ids], all_users_song_ids)
    similarity = similarity[0]
    similarity[int(target_id)] = -1
    print(similarity)
    most_similar_user_id = np.argmax(similarity)
    user_ids = list(user_ids)
    print(user_ids)
    user_ids.remove(int(target_id))
    while most_similar_user_id not in user_ids:
        most_similar_user_id = random.choice(user_ids)
    print("======",most_similar_user_id)
    recommended_songs = Collections.objects.filter(user_id=most_similar_user_id).values('song_id', 'song_name', 'song_url', 'song_pic')

    # return JsonResponse({'data': [{"song_id":"408814900","song_name":"借我","song_url":"http://m801.music.126.net/20240220225927/8ef2105b03ce1f36d0803e65984a5750/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/28481791211/c4c9/0b75/2d1d/9ed6a813cac06784a45c359f6d4165c8.mp3","song_pics":"http://p2.music.126.net/Eg4cy0_HIF2nrX2gMCsWkQ==/17967119509636556.jpg"}],'code':200})
    return JsonResponse({'data': list(recommended_songs),'code':200})


def _get_music(song_id):
    song_url = requests.get(base_url+'/song/url?id='+str(song_id))
    resp = song_url.json()
    song_url = resp['data'][0]['url']
    song_detail = requests.get(base_url+'/song/detail?ids='+str(song_id)).json()
    song_name = song_detail['songs'][0]['name']
    song_pic = song_detail['songs'][0]['al']['picUrl']
    return song_url,song_name,song_pic

def get_music(req):
    song_id = req.GET.get('song_id')
    song_url = requests.get(base_url+'/song/url?id='+song_id)
    resp = song_url.json()
    song_url = resp['data'][0]['url']
    song_detail = requests.get(base_url+'/song/detail?ids='+song_id).json()
    song_name = song_detail['songs'][0]['name']
    song_pic = song_detail['songs'][0]['al']['picUrl']

    return JsonResponse({'data': {'url': song_url, 'name': song_name, 'song_pic': song_pic,'song_id':song_id}, 'code': 200})


def search_view(req):
    q = req.GET.get('keywords')
    result = requests.get(base_url+'/search?type=1&keywords='+q).json()
    songs = result['result']['songs']
    results = []
    for song in songs:
        song_id = song['id']
        song_name = song['name']
        artists = song['artists'][0]['name']
        song_url ,song_name, song_pic = _get_music(song_id=song_id)
        results.append(
            {
                'song_id':song_id,
                'song_name':song_name,
                'artists':artists,
                'song_url':song_url,
                'song_pic':song_pic
            }
        )
    print(results)
    return JsonResponse({'data': results, 'code': 200})


def get_lyrics(req):
    song_id = req.GET.get('id')
    lyrics = requests.get(base_url+'/lyric?id='+song_id).json()
    text = lyrics['lrc']['lyric']
    url,name,pic = _get_music(song_id)
    return JsonResponse({'code':200,'data':{'lyrics':text,'song_id':song_id,'song_name':name,'song_pic':pic,'song_url':url}})
    



def get_hot_and_new_song(req):
    category = req.GET.get('cate')
    out = []
    t = req.GET.get('type',0)
    result = requests.get(base_url+f'/top/song?type={t}').json()['data']
    print(len(result))
    for song in result[:10]:
        song_id = song['id']
        print(song_id)
        url,name,pic = _get_music(song_id)
        out.append({'song_id':song_id,'song_name':song['name'],'song_pic':pic,'song_url':url})
    
    return JsonResponse({'code':200,'data':out})
    # elif category == 'hot':



def get_singer(req):
    cat = req.GET.get('cat')
    result = requests.get(base_url+f'/artist/list?cat={cat}').json()
    singers = result['artists']
    result= []
    for singer in singers:
        singer_id = singer['id']
        singer_name = singer['name']
        singer_pic = singer['picUrl']
        result.append({'singer_id':singer_id,'singer_name':singer_name,'singer_pic':singer_pic})
    return JsonResponse({'code':200,'data':result})


def get_singer_top_song(req):
    singer_id = req.GET.get('singer_id')
    result = requests.get(base_url+f'/artist/top/song?id={singer_id}').json()
    songs = result['songs']
    result = []
    for song in songs:
        song_id = song['id']
        url,name,pic = _get_music(song_id)
        result.append({'song_id':song_id,'song_name':name,'song_pic':pic,'song_url':url})
    return JsonResponse({'code':200,'data':result})